package com.czk.boot.spark.controller.rdd;

import org.apache.spark.api.java.JavaSparkContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/12/16 10:04
 */
@RestController
public class SparkRddController {
    @Autowired
    private JavaSparkContext jsc;

    @GetMapping("/pi")
    public Map<String, Double> pi() {
        Map<String, Double> map = new HashMap<>();
        List<Integer> l = new ArrayList<>(5);
        for (int i = 0; i < 5; i++) {
            l.add(i);
        }

        long count = jsc.parallelize(l).filter(i -> {
            double x = Math.random();
            double y = Math.random();
            return x * x + y * y < 1;
        }).count();
        map.put("data", 4.0 * count / 5);
        System.out.println("Pi is roughly " + 4.0 * count / 5);
        return map;
    }
}
